<template>
  <div class="dishes-management">
    <a-card title="菜品管理" class="card-container">
      <!-- 筛选区域 -->
      <div class="filter-container">
        <a-input
          v-model:value="searchKeyword"
          placeholder="搜索菜品名称"
          @change="handleSearch"
          style="width: 200px; margin-right: 16px"
        />
        <a-select
          v-model:value="categoryFilter"
          placeholder="选择分类"
          @change="handleCategoryFilterChange"
          style="width: 200px; margin-right: 16px"
        >
          <a-select-option
            v-for="category in getCategories"
            :key="category"
            :value="category"
          >
            {{ category }}
          </a-select-option>
        </a-select>
        <a-button @click="clearSearch">清空搜索</a-button>
      </div>
      <!-- 正常显示表格 -->
      <a-table
        :columns="columns"
        :data-source="data"
        :pagination="pagination"
        @change="handleTableChange"
        :row-key="(record) => record.id"
        class="table-container"
      >
        <template #image="{ record }">
          <a-image :src="record.image" alt="菜品图片" />
        </template>

        <template #action="{ record }">
          <a-button type="primary" @click="handleEdit(record)">编辑</a-button>
          <a-button type="primary" danger @click="confirmDelete(record.id)"
            >删除</a-button
          >
        </template>
      </a-table>
      <!-- 添加菜品模态框 -->
      <a-modal
        :visible="addModalVisible"
        title="添加菜品"
        @ok="handleAddDishOk"
        @cancel="handleAddDishCancel"
        class="modal-container"
      >
        <a-form :form="addDishForm" layout="vertical">
          <a-form-item label="菜品名称">
            <a-input v-model:value="addDishFormState.name" />
          </a-form-item>
          <a-form-item label="价格">
            <a-input-number v-model:value="addDishFormState.price" />
          </a-form-item>
          <a-form-item label="分类">
            <a-select v-model:value="addDishFormState.category">
              <a-select-option
                v-for="category in getCategories"
                :key="category"
                :value="category"
              >
                {{ category }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="图片">
            <a-upload
              name="image"
              :action="uploadUrl"
              :show-upload-list="false"
              @change="handleAddImageChange"
            >
              <a-button>上传图片</a-button>
            </a-upload>
            <img
              v-if="addDishFormState.image"
              :src="addDishFormState.image"
              alt="菜品图片"
              style="
                width: 50px;
                height: 50px;
                object-fit: cover;
                margin-top: 8px;
              "
            />
          </a-form-item>
        </a-form>
      </a-modal>
      <!-- 编辑菜品模态框 -->
      <a-modal
        :visible="editModalVisible"
        title="编辑菜品"
        @ok="handleEditDishOk"
        @cancel="handleEditDishCancel"
        class="modal-container"
      >
        <a-form :form="editDishForm" layout="vertical">
          <a-form-item label="菜品名称">
            <a-input v-model:value="editDishFormState.dishName" />
          </a-form-item>
          <a-form-item label="价格">
            <a-input-number v-model:value="editDishFormState.price" />
          </a-form-item>
          <a-form-item label="分类">
            <a-select v-model:value="editDishFormState.category">
              <a-select-option
                v-for="category in getCategories"
                :key="category"
                :value="category"
              >
                {{ category }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="图片">
            <a-upload
              name="image"
              list-type="picture-card"
              :action="'/api' + '/upload/image'"
              :show-upload-list="false"
              @change="handleEditImageChange"
            >
              <a-button>Upload</a-button>
            </a-upload>
            <a-image
              :width="200"
              src="C:\Users\27713\Pictures\uploads\96e3932d-b7e4-4079-ac23-438eea590b2e.png"
            />
          </a-form-item>
        </a-form>
      </a-modal>
      <!-- 添加菜品按钮 -->
      <a-button
        type="primary"
        @click="showAddDishModal"
        style="margin-top: 16px"
      >
        添加菜品
      </a-button>
      <a-button
        type="default"
        @click="handleRefresh"
        style="margin-top: 16px; margin-left: 16px"
      >
        刷新列表
      </a-button>
    </a-card>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from "vue";
import { FormInstance } from "ant-design-vue";
import { message, confirm } from "ant-design-vue";
import { uploadImage, requestData } from "@/utils/api";
export default {
  setup() {
    const columns = [
      {
        title: "菜名",
        dataIndex: "dishName",
        key: "dishName",
      },
      {
        title: "图片",
        dataIndex: "dishImage",
        slots: { customRender: "image" },
      },
      {
        title: "状态",
        dataIndex: "status",
      },
      {
        title: "价格",
        dataIndex: "price",
      },
      {
        title: "描述",
        dataIndex: "description",
      },

      { title: "操作", slots: { customRender: "action" } },
    ];

    // 静态菜品数据
    const data = ref([]);

    onMounted(async () => {
      // const { data: dishesData } = await requestData("/dishes");
      // data.value = dishesData;
    });

    const pagination = ref({ pageSize: 10, current: 1 });
    const searchKeyword = ref("");
    const categoryFilter = ref("");
    const addModalVisible = ref(false);
    const addDishForm = ref();
    const addDishFormState = reactive({
      name: "",
      price: null,
      category: "",
      image: "",
    });
    const editModalVisible = ref(false);
    const editDishForm = ref();
    const editDishFormState = reactive({});
    const uploadUrl = ref("https://example.com/upload"); // 替换为实际的图片上传接口地址

    // 处理图片上传
    const handleAddImageChange = (info) => {
      if (info.file.status === "done") {
        addDishFormState.image = info.file.response.url; // 假设接口返回图片的 URL
      }
    };

    const handleEditImageChange = async (info) => {
      if (info.file.status === "done") {
        editDishFormState.dishesImage = info.file.response.data; // 假设接口返回图片的 URL
      }
    };

    // 处理搜索
    const handleSearch = () => {
      pagination.value.current = 1;
    };

    // 处理分类筛选
    const handleCategoryFilterChange = (value) => {
      categoryFilter.value = value;
      pagination.value.current = 1;
    };

    // 清空搜索
    const clearSearch = () => {
      searchKeyword.value = "";
      categoryFilter.value = "";
      pagination.value.current = 1;
    };

    // 显示添加菜品模态框
    const showAddDishModal = () => {
      addModalVisible.value = true;
    };

    // 处理添加菜品确认
    const handleAddDishOk = () => {
      const newDish = {
        id: data.value.length + 1,
        ...addDishFormState,
      };
      data.value.push(newDish);
      addModalVisible.value = false;
      addDishForm.value?.resetFields();
      addDishFormState.image = "";
      message.success("菜品添加成功");
    };

    // 处理添加菜品取消
    const handleAddDishCancel = () => {
      addModalVisible.value = false;
      addDishForm.value?.resetFields();
      addDishFormState.image = "";
    };

    // 处理编辑菜品
    const handleEdit = (record) => {
      editModalVisible.value = true;
      Object.assign(editDishFormState, record);
    };

    // 处理编辑菜品确认
    const handleEditDishOk = () => {
      const index = data.value.findIndex(
        (item) => item.id === editDishFormState.id
      );
      if (index !== -1) {
        data.value[index] = {
          ...data.value[index],
          ...editDishFormState,
        };
      }
      editModalVisible.value = false;
      editDishForm.value?.resetFields();
      editDishFormState.image = "";
      message.success("菜品编辑成功");
    };

    // 处理编辑菜品取消
    const handleEditDishCancel = () => {
      editModalVisible.value = false;
      editDishForm.value?.resetFields();
      editDishFormState.image = "";
    };

    // 确认删除菜品
    const confirmDelete = (id) => {
      confirm({
        title: "确认删除此菜品吗？",
        onOk() {
          const index = data.value.findIndex((item) => item.id === id);
          if (index !== -1) {
            data.value.splice(index, 1);
            message.success("菜品删除成功");
          }
        },
      });
    };

    // 处理表格分页、排序、筛选变化
    const handleTableChange = (paginationInfo, filters, sorter) => {
      pagination.value = paginationInfo;
    };

    // 刷新列表
    const handleRefresh = () => {
      searchKeyword.value = "";
      categoryFilter.value = "";
      pagination.value.current = 1;
    };

    // 计算筛选后的数据
    const filteredData = computed(() => {
      let result = data.value;
      if (searchKeyword.value) {
        result = result.filter((item) =>
          item.name.includes(searchKeyword.value)
        );
      }
      if (categoryFilter.value) {
        result = result.filter(
          (item) => item.category === categoryFilter.value
        );
      }
      return result;
    });

    // 获取所有分类
    const getCategories = computed(() => {
      const categories = new Set();
      data.value.forEach((item) => {
        categories.add(item.category);
      });
      return Array.from(categories);
    });

    return {
      columns,
      data,
      pagination,
      searchKeyword,
      categoryFilter,
      addModalVisible,
      addDishForm,
      addDishFormState,
      editModalVisible,
      editDishForm,
      editDishFormState,
      handleEdit,
      confirmDelete,
      handleTableChange,
      handleSearch,
      handleCategoryFilterChange,
      clearSearch,
      showAddDishModal,
      handleAddDishOk,
      handleAddDishCancel,
      handleEditDishOk,
      handleEditDishCancel,
      filteredData,
      handleRefresh,
      uploadUrl,
      handleAddImageChange,
      handleEditImageChange,
      getCategories,
      uploadImage,
    };
  },
};
</script>

<style scoped>
.filter-container {
  margin-bottom: 16px;
}

.table-container {
  margin-bottom: 16px;
}

.modal-container {
  .ant-modal-body {
    padding: 24px;
  }
}
</style>
